package com.electric.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.electric.entity.User;

public class LoginInterceptor implements HandlerInterceptor, LoggerInterface {

	public void afterCompletion(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Object arg2,
			Exception arg3) throws Exception {
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String urlString = request.getRequestURI();
		logger.debug("拦截请求：");
		logger.debug(CommonStringUtils.getIpAddress(request));
		logger.debug(urlString);
		
		// 跳转到初始化的地址全部放行
		if("/init".equals(urlString.trim())){
			return true;
		}
		
		User user = (User) request.getSession().getAttribute("loginUser");
		if(user != null && StringUtils.isNotBlank(user.getUserId()) ){
			return true;
		}
		
		// 请求的路径
		String contextPath = request.getContextPath();

		response.sendRedirect(contextPath);
		return false;
	}

}